﻿var ns = namespace("kaskelot.sp.ui");

ns.sorting = function () {

    function initTableHeader(tableSelector, colName) {
        var headerLink = $(tableSelector + " .header." + colName + " a");

        headerLink.attr("data-tableselector", tableSelector);
        headerLink.attr("data-colName", colName);
        headerLink.append("<i class='icon-up-open'></i><i class='icon-down-open'></i>");
        headerLink.click(toggleTableSort);
    }

    function toggleTableSort() {
        var tableSelector = $(this).attr("data-tableselector");
        var colName = $(this).attr("data-colName");

        // Toggle any other active class
        $(tableSelector + " .header.active").removeClass("active");

        var header = tableSelector + " .header." + colName;
        var isDescending = $(header).hasClass("desc");
        $(header).toggleClass("desc");
        $(header).addClass("active");

        toggleSort(tableSelector + " tbody", "td." + colName, "tr", isDescending ? "asc" : "desc");
    }

    function toggleSort(content, sortBy, sortItem, sortOrder) {
        $(content).jSort({
            sort_by: sortBy,
            item: sortItem,
            order: sortOrder
        });
    }

    return {
        toggleSort: toggleSort,
        toggleTableSort : toggleTableSort,
        initTableHeader: initTableHeader,
    }
}();